package org.x4444.trans;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class TransJob extends Configured implements Tool {

    @Override
    public int run(String[] args) throws Exception {
        if (args.length != 2) {
            System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getSimpleName());
            ToolRunner.printGenericCommandUsage(System.err);
            return -1;
        }
        Configuration conf = new Configuration();
        conf.set("mapred.output.compress","true");
        conf.set("mapred.output.compression.type", "BLOCK");
        conf.set("mapred.output.compression","org.apache.hadoop.io.compress.DefaultCodec");
        
        conf.set("mapred.compress.map.output","true");
        conf.set("mapred.map.output.compression.codec","org.apache.hadoop.io.compress.SnappyCodec");
        
        Job job = new Job(conf);
        job.setJobName("Trans Job");
        job.setJarByClass(TransMapper.class);

        job.setMapperClass(TransMapper.class);
        job.setReducerClass(TransReducer.class);

        MultipleOutputs.addNamedOutput(job, "seq", SequenceFileOutputFormat.class, NullWritable.class, Text.class);

        // increase if you need sorting or a special number of files
        job.setNumReduceTasks(72);

        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        
        job.setInputFormatClass(TextInputFormat.class);
        // suppress part-r-00000 creation
        //job.setOutputFormatClass(NullOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // submit and wait for completion
        int res = job.waitForCompletion(true) ? 0 : 1;

        return res;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new TransJob(), args);
        System.exit(res);
    }

}
